<template>
  <div class="file-management-container">
    <a-tabs defaultActiveKey="1" @change="handleTabChange">
      <a-tab-pane tab="文件管理" key="1">
        <div class="file-operations">
          <a-button type="primary" @click="showNewFolderModal" icon="folder-add">
            新建文件夹
          </a-button>
          <a-upload
            name="file"
            :multiple="true"
            :action="uploadAction"
            :headers="headers"
            @change="handleUploadChange"
          >
            <a-button type="primary" icon="upload"> 上传文档 </a-button>
          </a-upload>
        </div>

        <a-table
          :columns="columns"
          :dataSource="fileList"
          :rowKey="record => record.id"
          :pagination="false"
          :loading="loading"
        >
          <template slot="operation" slot-scope="text, record">
            <a-button
              type="link"
              size="small"
              @click="showPermissionModal(record)"
            >
              权限管理
            </a-button>
            <a-button type="link" size="small" @click="handleDelete(record)">
              删除
            </a-button>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane tab="回收站" key="2">
        <a-table
          :columns="recycleColumns"
          :dataSource="recycleList"
          :rowKey="record => record.id"
          :pagination="false"
        >
          <template slot="operation" slot-scope="text, record">
            <a-button
              type="link"
              size="small"
              @click="handleRestore(record)"
            >
              恢复
            </a-button>
            <a-button type="link" size="small" @click="handleDeletePermanently(record)">
              彻底删除
            </a-button>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <!-- 新建文件夹模态框 -->
    <a-modal
      title="新建文件夹"
      :visible="newFolderModalVisible"
      @ok="handleNewFolderOk"
      @cancel="handleNewFolderCancel"
      :confirmLoading="newFolderLoading"
    >
      <a-form :form="form">
        <a-form-item label="文件夹名称">
          <a-input
            v-decorator="[
              'folderName',
              {
                rules: [
                  { required: true, message: '请输入文件夹名称' },
                  { max: 50, message: '名称不能超过50个字符' }
                ]
              }
            ]"
            placeholder="请输入文件夹名称"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限管理模态框 -->
    <a-modal
      title="权限管理"
      :visible="permissionModalVisible"
      @ok="handlePermissionOk"
      @cancel="handlePermissionCancel"
      width="700px"
    >
      <div class="permission-container">
        <div class="permission-roles">
          <h3>角色列表</h3>
          <a-checkbox-group
            v-model="selectedRoles"
            :options="allRoles"
            @change="onRoleChange"
          />
        </div>
        <div class="permission-details">
          <h3>权限详情</h3>
          <a-checkbox-group
            v-model="selectedPermissions"
            :options="permissionOptions"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: '1',
      loading: false,
      newFolderModalVisible: false,
      newFolderLoading: false,
      permissionModalVisible: false,
      form: this.$form.createForm(this),
      uploadAction: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', // 模拟上传地址
      headers: {
        authorization: 'authorization-text'
      },
      selectedFile: null,
      selectedRoles: [],
      selectedPermissions: [],
      allRoles: [
        { label: '管理员', value: 'admin' },
        { label: '编辑', value: 'editor' },
        { label: '查看者', value: 'viewer' },
        { label: '访客', value: 'guest' }
      ],
      permissionOptions: [
        { label: '查看', value: 'read' },
        { label: '编辑', value: 'edit' },
        { label: '删除', value: 'delete' },
        { label: '下载', value: 'download' },
        { label: '分享', value: 'share' }
      ],
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          width: 100
        },
        {
          title: '大小',
          dataIndex: 'size',
          key: 'size',
          width: 100
        },
        {
          title: '修改时间',
          dataIndex: 'modifiedTime',
          key: 'modifiedTime',
          width: 180
        },
        {
          title: '操作',
          key: 'operation',
          width: 150,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      recycleColumns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          width: 100
        },
        {
          title: '删除时间',
          dataIndex: 'deletedTime',
          key: 'deletedTime',
          width: 180
        },
        {
          title: '操作',
          key: 'operation',
          width: 150,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      fileList: [
        {
          id: '1',
          name: '项目文档',
          type: '文件夹',
          size: '-',
          modifiedTime: '2023-05-15 10:30',
          permissions: {
            admin: ['read', 'edit', 'delete', 'download', 'share'],
            editor: ['read', 'edit', 'download'],
            viewer: ['read', 'download']
          }
        },
        {
          id: '2',
          name: '需求说明书.pdf',
          type: 'PDF文档',
          size: '2.5MB',
          modifiedTime: '2023-05-10 14:20',
          permissions: {
            admin: ['read', 'edit', 'delete', 'download', 'share'],
            editor: ['read', 'edit', 'download']
          }
        },
        {
          id: '3',
          name: '用户画像.xlsx',
          type: 'Excel文档',
          size: '1.8MB',
          modifiedTime: '2023-05-08 09:15',
          permissions: {
            admin: ['read', 'edit', 'delete', 'download', 'share'],
            viewer: ['read', 'download']
          }
        }
      ],
      recycleList: [
        {
          id: '101',
          name: '旧版设计稿.psd',
          type: 'PSD文件',
          deletedTime: '2023-05-01 16:45'
        },
        {
          id: '102',
          name: '测试数据',
          type: '文件夹',
          deletedTime: '2023-04-28 11:20'
        }
      ]
    };
  },
  methods: {
    handleTabChange(key) {
      this.activeTab = key;
    },
    
    showNewFolderModal() {
      this.newFolderModalVisible = true;
    },
    
    handleNewFolderOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.newFolderLoading = true;
          // 模拟API调用
          setTimeout(() => {
            const newFolder = {
              id: Date.now().toString(),
              name: values.folderName,
              type: '文件夹',
              size: '-',
              modifiedTime: new Date().toLocaleString(),
              permissions: {
                admin: ['read', 'edit', 'delete', 'download', 'share']
              }
            };
            this.fileList.unshift(newFolder);
            this.newFolderModalVisible = false;
            this.newFolderLoading = false;
            this.form.resetFields();
            this.$message.success('文件夹创建成功');
          }, 800);
        }
      });
    },
    
    handleNewFolderCancel() {
      this.newFolderModalVisible = false;
      this.form.resetFields();
    },
    
    handleUploadChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.loading = false;
        // 模拟上传成功后添加到文件列表
        const newFile = {
          id: Date.now().toString(),
          name: info.file.name,
          type: this.getFileType(info.file.name),
          size: this.formatFileSize(info.file.size || Math.round(Math.random() * 5000000)),
          modifiedTime: new Date().toLocaleString(),
          permissions: {
            admin: ['read', 'edit', 'delete', 'download', 'share']
          }
        };
        this.fileList.unshift(newFile);
        this.$message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        this.loading = false;
        this.$message.error(`${info.file.name} 上传失败`);
      }
    },
    
    showPermissionModal(record) {
      this.selectedFile = record;
      this.selectedRoles = Object.keys(record.permissions || {});
      this.permissionModalVisible = true;
    },
    
    handlePermissionOk() {
      // 更新文件权限
      if (this.selectedFile) {
        const newPermissions = {};
        this.selectedRoles.forEach(role => {
          newPermissions[role] = this.selectedPermissions;
        });
        
        this.fileList = this.fileList.map(item => {
          if (item.id === this.selectedFile.id) {
            return {
              ...item,
              permissions: newPermissions
            };
          }
          return item;
        });
        
        this.$message.success('权限更新成功');
      }
      this.permissionModalVisible = false;
    },
    
    handlePermissionCancel() {
      this.permissionModalVisible = false;
    },
    
    onRoleChange(checkedValues) {
      // 当角色选择变化时，更新权限选项
      if (checkedValues.length > 0) {
        const firstRole = checkedValues[0];
        this.selectedPermissions = [...(this.selectedFile.permissions[firstRole] || [])];
      } else {
        this.selectedPermissions = [];
      }
    },
    
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除 "${record.name}" 吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 从文件列表移除，添加到回收站
          this.fileList = this.fileList.filter(item => item.id !== record.id);
          this.recycleList.unshift({
            ...record,
            deletedTime: new Date().toLocaleString()
          });
          this.$message.success('已移动到回收站');
        }
      });
    },
    
    handleRestore(record) {
      // 从回收站恢复
      this.recycleList = this.recycleList.filter(item => item.id !== record.id);
      const { deletedTime, ...rest } = record;
      this.fileList.unshift({
        ...rest,
        modifiedTime: new Date().toLocaleString()
      });
      this.$message.success('文件已恢复');
    },
    
    handleDeletePermanently(record) {
      this.$confirm({
        title: '确认彻底删除',
        content: `确定要永久删除 "${record.name}" 吗？此操作不可恢复！`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.recycleList = this.recycleList.filter(item => item.id !== record.id);
          this.$message.success('文件已永久删除');
        }
      });
    },
    
    getFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase();
      const typeMap = {
        pdf: 'PDF文档',
        doc: 'Word文档',
        docx: 'Word文档',
        xls: 'Excel文档',
        xlsx: 'Excel文档',
        ppt: 'PPT文档',
        pptx: 'PPT文档',
        jpg: '图片',
        jpeg: '图片',
        png: '图片',
        gif: '图片',
        txt: '文本文件',
        zip: '压缩文件',
        rar: '压缩文件',
        psd: 'PSD文件',
        ai: 'AI文件'
      };
      return typeMap[extension] || '文件';
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
};
</script>

<style scoped>
.file-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-operations {
  margin-bottom: 16px;
}

.file-operations button {
  margin-right: 8px;
}

.permission-container {
  display: flex;
}

.permission-roles {
  flex: 1;
  padding-right: 16px;
  border-right: 1px solid #e8e8e8;
}

.permission-details {
  flex: 2;
  padding-left: 16px;
}

.permission-container h3 {
  margin-bottom: 16px;
  color: rgba(0, 0, 0, 0.85);
}

.ant-checkbox-group {
  display: flex;
  flex-direction: column;
}

.ant-checkbox-wrapper {
  margin-bottom: 8px;
}
</style>